//
//  PictureSelectorViewController.swift
//  WeiBo_Private
//
//  Created by Yangperlove on 16/1/21.
//  Copyright © 2016年 Yangperlove. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let columnCount: CGFloat = 4
private let maxImageCount: Int = 9

class PictureSelectorViewController: UICollectionViewController, PictureCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    var imageList = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(PictureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // Do any additional setup after loading the view.
    }
    
    init() {
        let layout = UICollectionViewFlowLayout()
        let w = (screenSize.width - kStatusCellMargin * columnCount) / columnCount
        layout.itemSize = CGSize(width: w, height: w)
        layout.sectionInset = UIEdgeInsetsMake(20, 30, 20, 30)
        layout.minimumInteritemSpacing = 30
        layout.minimumLineSpacing = 30
        super.init(collectionViewLayout: layout)
        
        collectionView?.backgroundColor = UIColor.randomColor()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closePictureSelector")
        self.title = "选择图片"
        
    }
    
    //关闭图片选择器
    func closePictureSelector() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //MARK:实现代理方法
    func userWillSelectImage(cell: PictureCell) {
        if cell.image != nil {
            return
        }
        //1,实例化图片选择器
        let picker = UIImagePickerController()
        //2,设置pickerVC的代理
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }

    func userWillDeleteImage(cell: PictureCell) {
        //1.通过获取的cell 找到对应的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        imageList.removeAtIndex(indexPath?.item ?? 0)
        collectionView?.reloadData()
    }
    
    //MARK: pickerVC的代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        collectionView?.reloadData()
        
        //实现此代理方法需要手动dismiss掉pickVC
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        //如果已经是最大图片上传数时, 就不显示选择图片框
        let delta = imageList.count == maxImageCount ? 0 : 1
        return self.imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureCell
        cell.backgroundColor = UIColor.randomColor()
        cell.pictureCellDelegate = self
        
        //因为正常情况下, indexpath.item不可能和imageList.count 相等, 如果相等,说明是选择框,所以不设置图片
        cell.image = indexPath.item == imageList.count ? nil : imageList[indexPath.item]
    
        return cell
    }
}

//MARK:点击cell,要跳转页面,使用代理来跳转
//1,定义协议
protocol PictureCellDelegate: NSObjectProtocol {
    func userWillSelectImage(cell: PictureCell)
    func userWillDeleteImage(cell: PictureCell)
}

class PictureCell: UICollectionViewCell {
    
    //2,定义代理属性
    weak var pictureCellDelegate: PictureCellDelegate?
    
    var image: UIImage? {
        didSet {
            deleteButton.hidden = image == nil
            selectButton.setImage(image, forState: .Normal)
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:设置cell
    func setupUI() {
        addSubview(selectButton)
        addSubview(deleteButton)
        
        selectButton.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.right.top.equalTo(self)
        }
        
        selectButton.addTarget(self, action: "selectButtonDidClick", forControlEvents: .TouchUpInside)
        deleteButton.addTarget(self, action: "deleteButtonDidClick", forControlEvents: .TouchUpInside)

    }
    //MARK:调用代理方法
    func selectButtonDidClick() {
        self.pictureCellDelegate?.userWillSelectImage(self)
    }
    
    func deleteButtonDidClick() {
        self.pictureCellDelegate?.userWillDeleteImage(self)
    }
    
    lazy var selectButton: UIButton = UIButton(backImageName: "compose_pic_add", stretchable: false, imageName: nil, title: nil, fontSize: 1, titleColor: nil)
    
    lazy var deleteButton: UIButton = UIButton(backImageName: "compose_photo_close", stretchable: false, imageName: nil, title: nil, fontSize: 1, titleColor: nil)
}